/*
 * File: javaScriptServlet.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import data.FileReader;
import data.Memcache;
import fileHandlers.javaScriptMinifier;

/**
 * The Class javaScriptServlet.
 * 
 * @author Dude
 */
public class javaScriptServlet extends cookieServlet
{
    /*
     * (non-Javadoc)
     * 
     * @see
     * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
     * , javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        String files = req.getParameter("files");
        if (files != null)
        {
            String[] arFiles = files.split(",");
            for (int i = 0; i < arFiles.length; i++)
            {
                String fileName = "js/" + arFiles[i];
                String Contents = null;
                if (isDevMode(req))
                {
                    Memcache.clear();
                    Contents = FileReader.getFileContents(fileName);
                } else
                {
                    Contents = getMinifiedJs(fileName);
                }
                resp.getWriter().println(Contents);
            }
        }
    }

    /**
     * Get Minified js.
     * 
     * @param fileName
     *            the file name
     * @return the minified js
     */
    private static String getMinifiedJs(String fileName)
    {
        String Contents = Memcache.get("JSFILE" + fileName);
        if (Contents == null)
        {
            if ((Contents = FileReader.getFileContents(fileName.replace(".js",
                    ".min.js"))) == null)
            {
                Contents = javaScriptMinifier.minify(fileName);
            }
            Memcache.set("JSFILE" + fileName, Contents);
        }
        return Contents;
    }

    private static boolean isDevMode(HttpServletRequest req)
    {
        return "false".equals(getCookie(req, "useMinified"));
    }
}
